package activities;

import helper.GetMyScheduleHelper;
import helper.HttpHelper;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.facebook.Session;
import com.matchcalendar.R;

import dataFormat.CalendarTextData;
import dataFormat.FBUser;

import factories.CalendarTextDataFactory;
import fragments.MatchResultFragment;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;

public class MatchResultActivity extends FragmentActivity {
	private ViewPager matchSchedulePager;
	private Button buttonPrevious;
	private Bundle bundleFromPrevious;
	private List<MatchResultFragment> scheduleList = new ArrayList<MatchResultFragment>();
	private List<CalendarTextData> myScheduleDataList = new ArrayList<CalendarTextData>();
	private List<CalendarTextData> matchCalDataList;
	private Map<String, FBUser> idFriendsMap = new HashMap<String, FBUser>();
	private TextView textViewNowDate;
	private boolean haveGetData = false;
	private JSONArray matchResultJsonArr;
	
	public boolean isHaveGetData() {
		return haveGetData;
	}
	
	public JSONArray getMatchResultJsonArr() {
		return matchResultJsonArr;
	}
	
	public Map<String, FBUser> getIdFriendsMap() {
		return idFriendsMap;
	}
	
	public Bundle getBundleFromPrevious() {
		return bundleFromPrevious;
	}
	
	public List<MatchResultFragment> getScheduleList() {
		return scheduleList;
	}
	
	public ViewPager getMatchSchedulePager() {
		return matchSchedulePager;
	}
	
	public List<CalendarTextData> getMatchCalDataList() {
		return matchCalDataList;
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		bundleFromPrevious = getIntent().getExtras();
		initBundleFromPreviousData();
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_match_result);
		findView();
		setListenerOrAdapter();
		matchSchedulePager.setCurrentItem(0);
		new PostGetMySchedule().execute(getIntent().getExtras().getString("myFBID"));
	}
	
	private void initBundleFromPreviousData() {
		List<FBUser> friendList = bundleFromPrevious.getParcelableArrayList("friendList");
		
		for (FBUser friend: friendList)
			idFriendsMap.put(friend.getId(), friend);
		matchCalDataList = bundleFromPrevious.getParcelableArrayList("matchCalDataList");
	}

	private void findView() {
		matchSchedulePager = (ViewPager) findViewById(R.id.matchSchedulePager);
		buttonPrevious = (Button) findViewById(R.id.buttonPrevious);
		textViewNowDate = (TextView) findViewById(R.id.textViewNowDate);
	}
	
	private void setListenerOrAdapter() {
		matchSchedulePager.setAdapter(new MatchSchedulePagerAdapter(getSupportFragmentManager()));
		matchSchedulePager.setOnPageChangeListener(new MatchSchedulePagerPageChange());
		buttonPrevious.setOnClickListener(new ButtonPreviousClick());
	}
	
	private class MatchSchedulePagerAdapter extends FragmentPagerAdapter {
		public MatchSchedulePagerAdapter(FragmentManager fm) {
			super(fm);
			Calendar matchStartCal = Calendar.getInstance();
			Calendar matchOverCal = Calendar.getInstance();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月");
			
			matchStartCal.set(bundleFromPrevious.getInt("matchStartYear"),
					bundleFromPrevious.getInt("matchStartMonth"), bundleFromPrevious.getInt("matchStartDate"));
			matchStartCal.add(Calendar.DAY_OF_WEEK, -(matchStartCal.get(Calendar.DAY_OF_WEEK) - 1));
			matchOverCal.set(bundleFromPrevious.getInt("matchOverYear"),
					bundleFromPrevious.getInt("matchOverMonth"), bundleFromPrevious.getInt("matchOverDate"));
			textViewNowDate.setText(sdf.format(matchStartCal.getTime()));
			while (true) {
				Calendar weekCal = Calendar.getInstance();
				
				weekCal.set(matchStartCal.get(Calendar.YEAR), matchStartCal.get(Calendar.MONTH),
						matchStartCal.get(Calendar.DATE));
				scheduleList.add(new MatchResultFragment(false, weekCal, myScheduleDataList));
				if (matchStartCal.get(Calendar.WEEK_OF_YEAR) == matchOverCal.get(Calendar.WEEK_OF_YEAR))
					break;
				matchStartCal.add(Calendar.WEEK_OF_YEAR, 1);
			}
		}

		@Override
		public Fragment getItem(int index) {
			return scheduleList.get(index);
		}

		@Override
		public int getCount() {
			return scheduleList.size();
		}
	}
	
	private class MatchSchedulePagerPageChange implements ViewPager.OnPageChangeListener {

		@Override
		public void onPageScrollStateChanged(int arg0) {
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		@Override
		public void onPageSelected(int index) {
			Calendar cal = scheduleList.get(index).getWeekCal();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月");
			
			textViewNowDate.setText(sdf.format(cal.getTime()));
		}
	}
	
	private class ButtonPreviousClick implements Button.OnClickListener {

		@Override
		public void onClick(View v) {
			MatchResultActivity.this.finish();
		}
	}
	
	private class PostGetMySchedule extends GetMyScheduleHelper {
		private ProgressDialog proDialog;
		
		@Override
		protected void onPreExecute() {
			proDialog = ProgressDialog.show(MatchResultActivity.this, "媒合中", "正在為您行程媒合...");
			proDialog.setCancelable(false);
		}

		@Override
		protected void onPostExecute(String jsonString) {
			try {
				JSONArray respJsonArr = new JSONArray(jsonString);
				
				for (int i=0; i<respJsonArr.length(); i++) {
					CalendarTextData calTextData = CalendarTextDataFactory.newByJsonObject(
							respJsonArr.getJSONObject(i));
					
					myScheduleDataList.add(calTextData);
				}
				new PostMatch().execute();
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		
		private class PostMatch extends AsyncTask<Void, Void, String> {

			@Override
			protected String doInBackground(Void... params) {
				String respJsonString = null;
				
				try {
					JSONObject postJsonObj = new JSONObject();
					JSONArray friendsJsonArr = new JSONArray();
					JSONArray matchTimesJsonArr = new JSONArray();
					HttpResponse resp;
					List<CalendarTextData> matchCalDataList =
							bundleFromPrevious.getParcelableArrayList("matchCalDataList");
					
					for (String id: idFriendsMap.keySet())
						friendsJsonArr.put(id);
					for (CalendarTextData matchCalData: matchCalDataList) {
						JSONObject matchTimeJsonObj = new JSONObject();
						
						matchTimeJsonObj.put("day", matchCalData.getDay());
						matchTimeJsonObj.put("startTime", matchCalData.getStartHour() + ":" +
						matchCalData.getStartMinute());
						matchTimeJsonObj.put("overTime", matchCalData.getOverHour() + ":" +
						matchCalData.getOverMinute());
						matchTimesJsonArr.put(matchTimeJsonObj);
					}
					postJsonObj.put("friends", friendsJsonArr);
					postJsonObj.put("matchTimes", matchTimesJsonArr);
					resp = HttpHelper.executePost(
							"http://iculture.twgg.org/schedule/match.php", postJsonObj.toString());
					respJsonString = EntityUtils.toString(resp.getEntity());
				} catch (JSONException e) {
					e.printStackTrace();
				} catch (ParseException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
				return respJsonString;
			}
			
			@Override
			protected void onPostExecute(String respJsonString) {
				try {
					matchResultJsonArr = new JSONArray(respJsonString);
					for (int i=0; i<matchResultJsonArr.length(); i++) {
						JSONObject matchJsonObj = matchResultJsonArr.getJSONObject(i);
						String title = matchJsonObj.getInt("showUpRate") + "%";
						
						matchCalDataList.get(i).setTitle(title);
					}
					for (CalendarTextData calTextData: myScheduleDataList)
						scheduleList.get(0).addCalendarText(calTextData, null, null, Gravity.LEFT);
					for (int i=0; i<matchCalDataList.size(); i++) {
						MatchResultFragment schedule = scheduleList.get(0);
						CalendarTextData data = matchCalDataList.get(i);
						
						schedule.addCalendarText(data, schedule.new MatchScheduleTextClick(
								matchResultJsonArr.getJSONObject(i), data, schedule.getWeekCal()), null, Gravity.CENTER);
					}
					if (scheduleList.size() >= 2) {
						for (CalendarTextData calTextData: myScheduleDataList)
							scheduleList.get(1).addCalendarText(calTextData, null, null, Gravity.LEFT);
						for (int i=0; i<matchCalDataList.size(); i++) {
							MatchResultFragment schedule = scheduleList.get(1);
							CalendarTextData data = matchCalDataList.get(i);
							
							schedule.addCalendarText(data, schedule.new MatchScheduleTextClick(
									matchResultJsonArr.getJSONObject(i), data, schedule.getWeekCal()), null, Gravity.CENTER);
						}
					}
					haveGetData = true;
					proDialog.cancel();
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
	}
}
